package cn.doctor.assistant.pad.db;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.easemob.chat.EMMessage;
import com.easemob.chat.MessageEncoder;

import java.util.ArrayList;

import cn.doctor.assistant.pad.im.HXSDKHelper;

public class ChatDBManager extends DBBase{
	
	public static final String table = "chat";
	
	private static ChatDBManager instance;

	public synchronized static ChatDBManager getInstance() {
		if(instance == null){
			instance = new ChatDBManager();
		}
		return instance;
	}

	public synchronized boolean saveMessage(EMMessage message) {
		SQLiteDatabase sqlDB = DBHelper.getSQLiteDatabase();
		if(!tableIsExist(sqlDB, table)) return false;
		try {
			ContentValues contentValues = new ContentValues();
			
			contentValues.put("msgid", message.getMsgTime());
			//contentValues.put("msgid", message.getMsgId());
			
			contentValues.put("msgtime", Long.valueOf(message.getMsgTime()));
			contentValues.put("isacked", Integer.valueOf(message.isAcked ? 1 : 0));
			contentValues.put("isdelivered", Integer.valueOf(message.isDelivered ? 1 : 0));
			contentValues.put("msgdir", Integer.valueOf(message.direct.ordinal()));
			//contentValues.put("msgtype", Integer.valueOf(message.getChatType().ordinal()));
			EMMessage.Status localStatus = message.status;
			if (localStatus == EMMessage.Status.INPROGRESS) {
				localStatus = EMMessage.Status.CREATE;
			}
			contentValues.put("status", Integer.valueOf(localStatus.ordinal()));
			String str1;
			if (message.getFrom().equals(HXSDKHelper.getInstance().getHXId())) {
				str1 = message.getTo();
			} else {
				str1 = message.getFrom();
			}
			contentValues.put("participant", str1);
			contentValues.put("msgbody", MessageEncoder.getJSONMsg(message, true));
			if (message.getChatType() == EMMessage.ChatType.Chat) {
				contentValues.putNull("groupname");
			} else {
				contentValues.put("groupname", message.getTo());
			}
			contentValues.put("islistened", Integer.valueOf(message.isListened() ? 1 : 0));
			long id = sqlDB.insert("chat", null, contentValues);
			if(id > -1)
			return true;
		} catch (Exception localException) {
			localException.printStackTrace();
		}
		return false;

	}

	public synchronized EMMessage getLastMessage(String username) {
		SQLiteDatabase sqlDB = DBHelper.getSQLiteDatabase();
		if(!tableIsExist(sqlDB, table)) return null;
		Cursor cursor = null;

		cursor = sqlDB.rawQuery("select * from chat where participant = ? and groupname is null order by msgtime desc",
				new String[] { username });

		if (!cursor.moveToFirst()) {
			return null;
		}

		EMMessage msg = getMessage(cursor);
		cursor.close();

		return msg;
	}

	public synchronized ArrayList<EMMessage> getAllMessage(String username) {
		return getAllMessage(username, EMMessage.ChatType.Chat);
	}

	public synchronized ArrayList<EMMessage> getAllMessage(String username, EMMessage.ChatType chatType) {
		ArrayList<EMMessage> msgList = new ArrayList<>();

		SQLiteDatabase sqlDB = DBHelper.getSQLiteDatabase();

		if(!tableIsExist(sqlDB, table)) return msgList;
		
		Cursor cursor = null;
		if (chatType == EMMessage.ChatType.Chat) {
			cursor = sqlDB.rawQuery("select * from chat where participant = ? and groupname is null order by msgtime",
					new String[] { username });
		} else {
			cursor = sqlDB.rawQuery("select * from chat where groupname = ? order by msgtime",
					new String[] { username });
		}

		if (!cursor.moveToFirst()) {
			cursor.close();
			return msgList;
		}

		do {
			EMMessage message = getMessage(cursor);
			msgList.add(message);
		} while (cursor.moveToNext());
		cursor.close();

		return msgList;
	}
	
	public synchronized int getMessageCount(String username){
		int count = 0;
		try{
			SQLiteDatabase sqlDB = DBHelper.getSQLiteDatabase();
			if(!tableIsExist(sqlDB, table)) return 0;
			
			Cursor cursor = null;
			cursor = sqlDB.rawQuery("select count(1) from chat where participant = ? and groupname is null", new String[]{username});
			if(cursor.moveToFirst()){
				count = cursor.getInt(0);
			}
			cursor.close();
		}catch (Exception e){
			e.printStackTrace();
		}

		return count;
	}

	// XXX: msgId居然是会变的!!!(msgtime不变，应该是唯一的)
	public synchronized void updateMessageState(String msgId, String msgTime, EMMessage.Status state){
		SQLiteDatabase sqlDB = DBHelper.getSQLiteDatabase();
		ContentValues values = new ContentValues();
		values.put("status", state.ordinal()); // 0 成功 
		sqlDB.update("chat", values, "msgid = ? or msgtime = ?", new String[]{msgId, msgTime});
	}
	
	private synchronized EMMessage getMessage(Cursor paramCursor) {
		String msgBody = paramCursor.getString(paramCursor.getColumnIndex("msgbody"));
		EMMessage message = MessageEncoder.getMsgFromJson(msgBody);
		message.setMsgId(paramCursor.getString(paramCursor.getColumnIndex("msgid")));
		message.setMsgTime(paramCursor.getLong(paramCursor.getColumnIndex("msgtime")));
		int msgdir = paramCursor.getInt(paramCursor.getColumnIndex("msgdir"));
		if (msgdir == EMMessage.Direct.SEND.ordinal()) {
			message.direct = EMMessage.Direct.SEND;
		} else {
			message.direct = EMMessage.Direct.RECEIVE;
		}

		int msgStatus = paramCursor.getInt(paramCursor.getColumnIndex("status"));
		if (msgStatus == EMMessage.Status.CREATE.ordinal()) {
			message.status = EMMessage.Status.CREATE;
		} else if (msgStatus == EMMessage.Status.INPROGRESS.ordinal()) {
			message.status = EMMessage.Status.INPROGRESS;
		} else if (msgStatus == EMMessage.Status.SUCCESS.ordinal()) {
			message.status = EMMessage.Status.SUCCESS;
		} else if (msgStatus == EMMessage.Status.FAIL.ordinal()) {
			message.status = EMMessage.Status.FAIL;
		}

		int isAcked = paramCursor.getInt(paramCursor.getColumnIndex("isacked"));
		if (isAcked == 0) {
			message.isAcked = false;
		} else {
			message.isAcked = true;
		}

		int isDelivered = paramCursor.getInt(paramCursor.getColumnIndex("isdelivered"));
		if (isDelivered == 0) {
			message.isDelivered = false;
		} else {
			message.isDelivered = true;
		}

		int isListened = paramCursor.getInt(paramCursor.getColumnIndex("islistened"));
		message.setListened(isListened == 1);
		message.setUnread(false);

		String groupName = paramCursor.getString(paramCursor.getColumnIndex("groupname"));
		if (groupName == null) {
			message.setChatType(EMMessage.ChatType.Chat);
		} else {
			// int msgType =
			// paramCursor.getInt(paramCursor.getColumnIndex("msgtype"));
			message.setChatType(EMMessage.ChatType.GroupChat);
			/*
			 * if (msgType == EMMessage.ChatType.ChatRoom.ordinal()) {
			 * message.setChatType(EMMessage.ChatType.ChatRoom); }
			 */
			message.setTo(groupName);
		}
		return message;
	}

}
